package com.shuwang.geguo.indexview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * 1、初始化画笔
 * 2、绘制字母表：需要确定坐标（需要测量view的宽高）
 * 3、添加触摸监听
 * 4、开放接口
 */
public class MyIndex extends View {

    private Paint mPaint;

//  需要绘制的字母表
        /*索引的字母，可以添加自己想要的*/
private String mIndex[] = {"A","B","C","D","E","F","G","H","I",
        "J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
    private int cellWidth;
    private float textHeight;
    private int currentIndex;
    private SelectIndexListener selectIndexListener;

    public MyIndex(Context context) {
        super(context);
    }

    public MyIndex(Context context, AttributeSet attrs) {
        super(context, attrs);
        initCustomView();
    }

    public MyIndex(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initCustomView();
    }

    /**
     * 初始化自定义布局
     */
    private void initCustomView() {
        /*
        *
        标题	相关方法	备注
        色彩	setColor setARGB setAlpha	设置颜色，透明度
        大小	setTextSize	设置文本字体大小
        字体	setTypeface
        * */
        mPaint = new Paint();

        mPaint.setTypeface(Typeface.DEFAULT);
//      字体的大小根据高度动态计算（不过不能放在这里）
//      mPaint.setTextSize(cellHeight*3.0f/4.0f);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (int i=0;i<mIndex.length;i++){
            mPaint.setTextSize(textHeight*3.0f/4.0f);
//          选中的时候将字母的颜色设置为灰色
//            (currentIndex != i ? color : color = Color.GRAY) =Color.BLACK; 注意三元运算符不能单独运算
            mPaint.setColor(currentIndex==i?Color.GRAY:Color.BLACK);
            Rect textRect=new Rect();
            mPaint.getTextBounds(mIndex[i],0,mIndex[i].length(),textRect);

//          x 相对起始坐标：view的宽度的一半减去 text宽度的一半
            float fromX = cellWidth/2.0f - textRect.width()/2.0f;
//          y 相对起始坐标：字所有的高度*i+每个单元的高度 - 字高的一半
            float endY = textHeight*i + textHeight/2.0f+textRect.height()/2.0f;
            canvas.drawText(mIndex[i],fromX,endY,mPaint);
//          重置画笔
            mPaint.reset();
        }

    }

/*    *//**
     * 根据父控件给定的测量参考值来测量view的大小
     * 注意：这里只是大小，没有涉及到view的位置
     *//*
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//        不要系统的测量，自己重新确定测量setMeasureDimension(400,800) 该方法用于确定View的大小
        setMeasuredDimension(measureWidth(widthMeasureSpec),measureHeight(heightMeasureSpec));
    }*/


//  如果不使用onMeasure方法
//  使用onSizeChanged同样可以拿到View的宽度和高度

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        textHeight = h*1.0f/mIndex.length;
        cellWidth=w;
    }

    /**
     * @param heightMeasureSpec
     * @return view的高度
     */
    private int measureHeight(int heightMeasureSpec) {
        int height = 0;
        int mode = MeasureSpec.getMode(heightMeasureSpec);
        int size = MeasureSpec.getSize(heightMeasureSpec);

        if (mode == MeasureSpec.EXACTLY){
            height = size;
        }else {
            int desire =  size + getPaddingTop()+getPaddingBottom();
            if (mode==MeasureSpec.AT_MOST){
                height=Math.min(desire,size);
            }else if (mode==MeasureSpec.UNSPECIFIED){
                height=desire;
            }
        }
//        cellHeight=height;
//      计算出每个字母均分的距离
        textHeight = height*1.0f/mIndex.length;
        return height;

    }

    /**
     * @param widthMeasureSpec
     * @return view的宽度
     */
    private int measureWidth(int widthMeasureSpec) {
        //      拿到父控件给定的测量模式
        int mode = MeasureSpec.getMode(widthMeasureSpec);
        int size = MeasureSpec.getSize(widthMeasureSpec);
        int width = 0;
//      如果是精确测量模式
        if (mode ==MeasureSpec.EXACTLY){
            width = size;
        }else{
//          动态计算view的大小
            int desire =  size +getPaddingLeft() +getPaddingRight();
            if (mode ==MeasureSpec.AT_MOST){
                width = Math.min(desire,size);
            }else if (mode == MeasureSpec.UNSPECIFIED){
//                如果大小未指定，就动态计算得了
                width=desire;
            }
        }
        cellWidth = width;
        return width;
    }

    /**
     * @param event
     * @return 根据触摸事件 调整文字的颜色和大小
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
//      拿到点击的坐标，判断在哪个区域
        float position = event.getY();
//      当前位置
        currentIndex = (int) (position/textHeight);
        if(currentIndex >= 0 && currentIndex < mIndex.length){
            selectItem(currentIndex);
        }

//      请求重绘
        invalidate();
//      如果是ViewGroup则要请求重新布局
//      requestLayout();
        return true;//处理该事件
    }

    private void selectItem(int currentIndex) {
        if (selectIndexListener!=null){
            selectIndexListener.showChoice(currentIndex,mIndex[currentIndex]);
        }
    }

//  设置一个接口
    interface SelectIndexListener{
        void showChoice(int position,String value);
    }

    public void setOnSelectIndexListener(SelectIndexListener listener){
        selectIndexListener = listener;
    }

}
